<template>
  <div class="edit-area">
    <el-form-item label="富文本编辑区背景颜色" class="editor-info" v-if="true">
      <el-color-picker
          size="small"
          show-alpha
          :predefine="predefineColors"
          v-model="background"
      />
    </el-form-item>

    <el-upload
        name="file"
        ref="upload"
        v-if="this.type === 'url'"
        :headers="headers"
        :action="uploadUrl"
        style="display: none"
        :show-file-list="false"
        :before-upload="handleBeforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
    />

    <div class="editor" ref="editor" :style="styles"></div>

    <!--轮播图弹层-->
    <updatePicture
        @handleSure="handleSure"
        @handleCancel="handleCancel"
        :info="formCarouselInfo.info"
        :visible="formCarouselInfo.visible"
    />

  </div>
</template>

<script>
import Quill from "quill";
import {apiRoot} from "@s/ajax";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import ImageResize from "quill-image-resize-module"; // 引用
import {ImageDrop} from "quill-image-drop-module";

Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize);   // 注册
// 新建自定义的样式
import "@/components/assets/style/quillEditor.scss";
import updatePicture from "@c/public/layer/template/updatePicture";
import * as types from "@c/public/form-designer/devType/datas-types";

// 行高设定
const lineHeight = [...Array(16).keys()].map((x) => `${(100 + x * 10) / 100}`);
const parchment = Quill.import('parchment');
const lineHeightConfig = {
  scope: parchment.Scope.INLINE,
  whitelist: lineHeight,
};
const lineHeightStyle = new parchment.Attributor.Style(
    'lineHeight',
    'line-height',
    lineHeightConfig
);
// 最核心的两行代码
Quill.register({'formats/lineHeight': lineHeightStyle}, true);
Quill.register({lineHeightStyle: true});


const sizes = [false, "16px", "20px", "28px", "30px", "32px", "34px", "36px", "38px", "40px", "42px", "44px", "46px", "48px", "50px", "52px", "54px", "56px", "58px", "60px", "70px", "80px", "90px", "100px", "110px", "120px", "130px", "140px", "150px"];
const Size = Quill.import("formats/size");
Size.whitelist = sizes;
export default {
  name: "Editor",

  components: {updatePicture},

  props: {
    /* 编辑器的内容 */
    value: {
      type: String,
      default: "",
    },
    /* 高度 */
    height: {
      type: Number,
      default: null,
    },
    /* 最小高度 */
    minHeight: {
      type: Number,
      default: null,
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false,
    },
    // 上传文件大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    /* 类型（base64格式、url格式） */
    type: {
      type: String,
      default: "url",
    }
  },

  data() {
    return {
      uploadUrl: `${apiRoot('/upload', 'BaseApi')}`, 	// 服务器上传地址
      headers: {
        // Authorization: `Bearer ${getToken()}`
      },
      Quill: null,
      currentValue: "",
      pictureInfo: {
        visible: false,
        info: 1,
      },
      // 轮播图
      formCarouselInfo: {
        visible: false,
        info: '',
      },
      options: {
        placeholder: "请输入内容",
        readOnly: this.readOnly,
        theme: "snow",
        bounds: document.body,
        syntax: true, //语法检测
        modules: {
          toolbar: {
            container: [
              // ["bold", "italic", "underline", "strike"],       // 加粗 斜体 下划线 删除线
              ["bold", "italic"],       // 加粗 斜体 下划线 删除线
              // ["blockquote", "code-block"],                    // 引用  代码块
              // [{list: "ordered"}, {list: "bullet"}],           // 有序、无序列表
              // [{indent: "-1"}, {indent: "+1"}],                // 缩进
              [{size: sizes}],                                 // 配置字号
              // [{ lineheight: lineHeight }],                    // 行高
              // [{header: [1, 2, 3, 4, 5, 6, false]}],        // 标题
              [{color: []}, {background: []}],                 // 字体颜色、字体背景颜色
              [{align: []}],                                   // 对齐方式
              ["clean"],                                       // 清除文本格式
              ["image"]                                        // 链接、图片、视频
              // ["link", "image", "video"]                    // 链接、图片、视频
            ],
            handlers: {
              lineheight: (value) => {
                if (value) {
                  let quill = this.$refs.editor;
                  console.log(quill)
                  // quill.format("lineHeight", value);
                }
              }
            },
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white"
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          },
        },
      },
      predefineColors: types['predefineColors'],
      background: '#F8F8F8'
    };
  },

  computed: {
    // 定义高度
    styles() {
      let style = {};
      if (this.minHeight) {
        style.height = `${this.minHeight}px`;
      }
      if (this.height) {
        style.height = `${this.height}px`;
      }
      style.background = `${this.background}`
      return style;
    },
  },

  mounted() {
    this.init();
  },

  methods: {
    // 初始化组件
    init() {
      const editor = this.$refs.editor;
      this.Quill = new Quill(editor, this.options);
      // 如果设置了上传地址则自定义图片上传事件
      if (this.type === 'url') {
        let toolbar = this.Quill.getModule("toolbar");
        toolbar.addHandler("image", (value) => {
          // 自定义资源库选择时间
          if (value) {
            let params = Object();
            // 查找资源库对应的资源
            Reflect.set(params, 'type', 'image');
            // 修改对应的字段
            Reflect.set(params, 'updataType', 'carouselInfo');
            // 旧的数据
            Reflect.set(params, 'content', []);
            // 是否支持多图片
            Reflect.set(params, 'multiple', false);
            Reflect.set((this.formCarouselInfo), 'visible', true);
            Reflect.set((this.formCarouselInfo), 'info', params);

          } else {
            this.quill.format('image', false)
          }
          // 图片上传时间
          // this.uploadType = "image";
          // if (value) {
          //   this.$refs.upload.$children[0].$refs.input.click();
          // } else {
          //   this.quill.format("image", false);
          // }
        });
      }
      this.Quill.pasteHTML(this.currentValue);
      this.Quill.on("text-change", (delta, oldDelta, source) => {
        const html = this.$refs.editor.children[0].innerHTML;
        const text = this.Quill.getText();
        const quill = this.Quill;
        this.currentValue = html;
        this.$emit("input", html);
        this.$emit("on-change", {html, text, quill});
      });
      this.Quill.on("text-change", (delta, oldDelta, source) => {
        this.$emit("on-text-change", delta, oldDelta, source);
      });
      this.Quill.on("selection-change", (range, oldRange, source) => {
        this.$emit("on-selection-change", range, oldRange, source);
      });
      this.Quill.on("editor-change", (eventName, ...args) => {
        this.$emit("on-editor-change", eventName, ...args);
      });
    },

    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },

    // 上传成功
    handleUploadSuccess(res, file) {
      // 获取富文本组件实例
      let quill = this.Quill;
      // 如果上传成功
      if (res.code === 200) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.url为服务器返回的图片地址
        console.log(res, 'res');
        quill.insertEmbed(length, "image", process.env.VUE_APP_BASE_API + res.data.storePath);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
    },

    // 上传失败
    handleUploadError() {
      this.$message.error("图片插入失败");
    },

    // 取消图片弹层
    handleCancel() {
      Reflect.set((this.formCarouselInfo), 'visible', false);
    },

    //图片弹层的确定
    handlePictureSure(val) {
      const self = this;
      if (!!val) {
        let quill = self.Quill;
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.url为服务器返回的图片地址
        quill.insertEmbed(length, "image", `${val}`);
        // 调整光标到最后
        quill.setSelection(length + 1);
        self.handleCancel();
      } else {
        self.$message({
          message: '很抱歉，图片插入失败!',
          type: 'warning'
        });
      }
    },

    handleSure(info) {
      const self = this;
      console.log('-----');
      console.log(info)
      if (!!info && (info.val)) {
        let pictureInfo = (info.val);
        let quill = self.Quill;
        // 获取光标所在位置
        let length = quill.getSelection().index;
        if (self.$lodash.isArray(pictureInfo)) {
          if (!!(pictureInfo?.length)) {
            quill.insertEmbed(length, "image", `${pictureInfo[0].url}`);
          }
        } else if (self.$lodash.isPlainObject(pictureInfo)) {
          quill.insertEmbed(length, "image", `${pictureInfo.url}`);
        } else {
          quill.insertEmbed(length, "image", `${pictureInfo}`);
        }
        // 调整光标到最后
        quill.setSelection(length + 1);
        self.handleCancel();
      } else {
        self.$message({
          message: '很抱歉，图片插入失败!',
          type: 'warning'
        });
      }
    },

  },

  // 销毁组件
  beforeDestroy() {
    this.Quill = null;
  },

  watch: {
    value: {
      handler(val) {
        if (val !== this.currentValue) {
          this.currentValue = val === null ? "" : val;
          if (this.Quill) {
            this.Quill.pasteHTML(this.currentValue);
          }
        }
      },
      immediate: true,
    },
  },

};
</script>

<style lang="scss">
.edit-area {
  margin-bottom: 20px;

  .editor-info {
    overflow: hidden;
    padding-top: 10px;
    padding-left: 10px;
    margin-bottom: 0 !important;

    .el-form-item__label {
      width: auto !important;

    }

    .el-form-item__content {
      height: auto;
      overflow: hidden;
    }
  }
}

.editor {
  white-space: pre-wrap !important;
  line-height: normal !important;
  overflow: auto;
  background: #F8F8F8;

  ::-webkit-scrollbar {
    width: 4px;
  }
}

.ql-toolbar {
  white-space: pre-wrap !important;
  line-height: normal !important;

  button:hover::after {
    content: attr(title); /* 使用按钮的title属性作为显示的文本 */
    position: absolute;
    white-space: nowrap;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
    padding: 4px 8px;
    border-radius: 3px;
    background-color: black;
    color: white;
    font-size: 12px;
    visibility: visible;
    opacity: 1;
    z-index: 10;
  }

  button::after {
    visibility: hidden;
    opacity: 0;
    transition: visibility 0s, opacity 0.5s linear;
  }
}

.quill-img {
  display: none;
}

// 字号大小
.ql-snow {
  .ql-formats {
    .ql-size {
      .ql-active,
      .ql-picker-label,
      .ql-picker-item {
        &::before {
          border: none;
          font-size: 14px !important;
        }
      }

      .ql-picker-options {
        height: 260px;
        overflow: auto;
      }
    }
  }
}

.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}

.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0;
  content: "保存";
  padding-right: 0;
}

.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}

.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}

.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}

</style>